package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto == null && dto.getEquipmentId() == null &&
                StringUtils.isBlank(dto.getPhone()) &&
                StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //是否是登录
        if (StringUtils.isNotBlank(dto.getPhone()) &&
                StringUtils.isNotBlank(dto.getPassword())) {
            //根据手机号查询用户信息，获取密码和盐
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus, 0));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }
            String dbpassword = apUser.getPassword();
            String salt = apUser.getSalt();

            //比对密码
            String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!dbpassword.equals(newPassword)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号或密码错误");
            }
            //生成JWT的token令牌并返回
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));

            apUser.setPassword(null);
            apUser.setSalt(null);

            map.put("user",apUser);
            return ResponseResult.okResult(map);
        } else {//设备登录
            HashMap<String, Object> map = new HashMap<>();
            //map.put("token", AppJwtUtil.getToken(dto.getEquipmentId().longValue()));
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }



    }
}
